package cn.topkinson.jedis;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashSet;
import java.util.Set;

/**
 * @Author huangzihao
 * @Date 2020/12/16 21:01
 */
public class Application {

    private static JedisCluster jedis;

    static {
        // 添加集群的服务节点Set集合
        Set<HostAndPort> hostAndPortsSet = new HashSet<HostAndPort>();
        // 添加节点
        hostAndPortsSet.add(new HostAndPort("192.168.132.135", 7001));
        hostAndPortsSet.add(new HostAndPort("192.168.132.135", 7002));
        hostAndPortsSet.add(new HostAndPort("192.168.132.135", 7003));
        hostAndPortsSet.add(new HostAndPort("192.168.132.135", 7004));
        hostAndPortsSet.add(new HostAndPort("192.168.132.135", 7005));
        hostAndPortsSet.add(new HostAndPort("192.168.132.135", 7006));

        // Jedis连接池配置
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        // 最大空闲连接数, 默认8个
        jedisPoolConfig.setMaxIdle(100);
        // 最大连接数, 默认8个
        jedisPoolConfig.setMaxTotal(500);
        //最小空闲连接数, 默认0
        jedisPoolConfig.setMinIdle(0);
        // 获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常, 小于零:阻塞不确定的时间,  默认-1
        jedisPoolConfig.setMaxWaitMillis(2000); // 设置2秒
        //对拿到的connection进行validateObject校验
        jedisPoolConfig.setTestOnBorrow(true);

        //创建redisCluster
        jedis = new JedisCluster(hostAndPortsSet, jedisPoolConfig);
    }

    public static void main(String[] args) {
        String key = "name:002";
        System.out.println("判断某个键是否存在："+jedis.exists(key));
        System.out.println("新增<'"+key+"','kinson'>的键值对："+jedis.set(key, "kinson"));
        System.out.println("是否存在:"+jedis.exists(key));

        /**
         * 判断某个键是否存在：false
         * 新增<'name:001','kinson'>的键值对：OK
         * 是否存在:true
         */
    }
}
